import axios from 'axios';
import { getToken, serverUrl } from './tools';

const instance = axios.create({
  //超时时间
  timeout: 3000,
  //服务器地址
  baseURL: serverUrl,
});

// 添加请求拦截器
instance.interceptors.request.use(
  function (config) {
    //名字由服务器端定
    config.headers.token = getToken();
    return config;
  },
  function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);

// 添加响应拦截器
instance.interceptors.response.use(
  (response) => {
    return response.data;
  },
  (error) => {
    if (error?.status === 401) {
      return Promise.reject(error);
    }
  }
);

export const get = (url: any, params: any) => instance.get(url, { params });
export const post = (url: any, data: any) => instance.post(url, data);
export const patch = (url: any, data: any) => instance.patch(url, data);
export const put = (url: any, data: any) => instance.put(url, data);
export const del = (url: any) => instance.delete(url);
